<script setup lang="jsx">
import {inject, ref, reactive, computed, onMounted} from 'vue'
import waybill from '@/api/abroad/waybill'
import {Message, Modal} from '@arco-design/web-vue'
import dicthelpApi from "@/api/dicthelpApi.js";
import common from "@/api/common.js";
import {getDictData} from "@/utils/crud/dictNew.js";
import tool from '@/utils/tool'
import * as XLSX from 'xlsx';
import uploadConfig from '@/config/upload'
import addRess from "@/views/abroad/waybill/components/address.vue";
import fileType from "@/views/components/fileType.vue";


const loading = ref(false)
const columnsDist = inject('columnsDist')
const span = ref(8)
const formRef = ref(null)
const service_id_list = ref('')
const addressRef = ref()
const filetypeRef= ref()
const tableEditingIndex = ref({})
const tableFile=ref({})

// 开始编辑
const startEditing = (row_index) => {
  for (const tableEditingIndexKey in tableEditingIndex.value) {
    tableEditingIndex.value[tableEditingIndexKey] = false
  }
  tableEditingIndex.value[row_index] = true
};

// 停止编辑
const stopEditing = () => {
  tableEditingIndex.value = {}
};
// 表单数据
const rules = {
  type: [{required: true, message: '请选择类型', validateTrigger: 'blur'},],
  depot_id: [{required: true, message: '请选择转运仓库', validateTrigger: 'blur'},],
  number: [{required: true, message: '请输入提单号', validateTrigger: 'blur'},],
  container_no: [{required: true, message: '请输入柜号', validateTrigger: 'blur'},],
  container_type: [{required: true, message: '请选择柜型', validateTrigger: 'blur'},],
  service_id: [{required: true, message: '请选择服务项目', validateTrigger: 'blur'},],
  carrier: [{required: true, message: '请选择承运商', validateTrigger: 'blur'},],
  etd: [{required: true, message: '请选择ETD', validateTrigger: 'blur'},],
  eta: [{required: true, message: '请选择ETA', validateTrigger: 'blur'},],
  received_at: [{required: true, message: '请选择入仓时间', validateTrigger: 'blur'},],
  departure: [{required: true, message: '请选择起运港', validateTrigger: 'blur'},],
  destination: [{required: true, message: '请选择目的港', validateTrigger: 'blur'},],
}
const formData = ref({
  id: '',
  depot_id: "",
  number: "",
  container_no: "",
  container_type: "",
  type: "1",
  service_id: "",
  carrier: "",
  etd: "",
  eta: "",
  received_at: "",
  departure: "",
  destination: "",
  exportwith: "0",
  frame: "0",
  // weight_volume: '1',
  shipments: [],
  files: []
})
const visible = ref(false)
const waybillServiceTypeList = ref([])
const waybillServiceShipmentTypeList = ref([])
//服务项目
const waybillServiceTypeListData = () => {
  dicthelpApi.waybillServiceTypeList({type: formData.value.type}).then(res => {
    waybillServiceTypeList.value = res.data
  })
}
//服务项目发生改变服务类型
const waybillServiceShipmentTypeListData = () => {
  dicthelpApi.waybillServiceShipmentTypeList({service: formData.value.service_id}).then(res => {
    res.data.map((item, index) => {
      item.id = item.id.toString()
    })
    waybillServiceShipmentTypeList.value = res.data
    // if(resData){
    //   resData?.shipment?.map((item, index) => {
    //   formData.value.shipments[index].service_type_id = Number(formData.value.shipments[index].service_type_id)
    //   // serviceTypeChang(item.service_type_id, item, 'init')
    // })
    // loading.value=false
    // }
  })
}

const CBMtoTrayCountEstimateHalf = 0.9
const handleUpload = (fileList, files) => {
  loading.value = true
  if (!files.file) {
    Modal.open({content: '没有选择文件'})
    loading.value = false
    return
  }
  const reader = new FileReader();
  reader.onload = (event) => {
    const data = new Uint8Array(event.target.result);
    const workbook = XLSX.read(data, {type: 'array'});
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    // 这里可以根据需求对解析后的数据进行进一步处理，比如触发一个自定义事件，将数据传递给父组件
    const shipment = []
    for (let k in jsonData) {
      let i = jsonData[k]
      let service_type
      waybillServiceShipmentTypeList.value?.map(t => {
        if (t.name === i.服务类型)
          service_type = t
      })
      if (!service_type) {
        if(i.服务类型){
          Modal.open({content: '服务类型' + i.服务类型 + '不存在'})
        }else{
           Modal.open({content: '服务类型不存在'})
        }
        loading.value = false
        return 1;
      }

      shipment[k] = {
        id: new Date().getTime() + k,
        urgent: i.是否加急 ? 1 : 0,
        is_intercept: i.是否拦截 ? 1 : 0,
        service_type_id: service_type.id,
        shipment_no: i.箱唛,
        parcel_count_estimate: i['CTNS(件数)'],
        weight: i.Weight,
        volume: i.CBM,
        fba_id: i.ID,
        po_number: i.PO,
        remark: i.备注,
      }
      getTrayCount(shipment[k], i.CBM)
      serviceTypeChang(service_type.id, shipment[k], i.目的地)
      formData.value.shipments = shipment
      loading.value = false
    }
  };
  reader.readAsArrayBuffer(files.file)
  tableFile.value=files
};

const getTrayCount = function (shipment, volume) {
  if (CBMtoTrayCountEstimateHalf !== 0) {
    // 以0.5 为步进，计算托盘数量
    shipment.tray_count_estimate = Math.ceil(volume / CBMtoTrayCountEstimateHalf) * 0.5;
  } else {
    shipment.tray_count_estimate = 0;
  }
}
//添加目的地
const addRessTap = () => {
  addressRef.value.open();
}
//下载模版
const downloadTap = async () => {
  const res = await waybill.downloadTemplate({type: 'sea_waybill_list'})
  let storeMode = getStoreMode(res.data.storage_mode)
  if (storeMode !== 'LOCAL') {
    Message.info('处理中...')
    const domain = uploadConfig.storage[storeMode]
    window.location.href = domain + res.data.url
  }
}
const getStoreMode = (mode) => {
  return uploadConfig.storageMode[mode.toString()]
}
//详情
const infoGet = (id) => {
  waybill.read(id).then(res => {
    formData.value = res.data
    formData.value.type = res.data.type.toString()
    formData.value.shipments = res.data.shipment
    upload.fileList = res.data.file
    loading.value = false
  })

}
const addressListChang = (data) => {
  const type = data.service_type_id
  const serviceType = waybillServiceShipmentTypeMap.value[type]?.type
  return addressList.value[serviceType] ?? []
}
//类型发生改变
const typeChang = () => {
  waybillServiceTypeList.value = []
  formData.value.service_id = ''
  waybillServiceTypeListData()
}
const waybillServiceShipmentTypeMap = computed(() => {
  let result = {};
  waybillServiceShipmentTypeList.value?.map(i => {
    result[i.id] = i
  })
  return result
})
const addressList = ref({})
const addressListMap = computed(() => {
  return Object.keys(addressList.value).reduce((acc, cur) => {
    // 将 acc 转换为对象, value 为key
    acc[cur] = Object.keys(addressList.value[cur]).reduce((acc1, cur1) => {
      acc1[addressList.value[cur][cur1].value] = addressList.value[cur][cur1]
      return acc1
    }, {})
    return acc
  }, {})
})
onMounted(() => {
  addAll()
})
const addAll = () => {
  dicthelpApi.allAddress().then(res => {
    addressList.value = res.data
  })
}
const downloadAdd=()=>{
  filetypeRef.value.onShow();
}
//上传文件
const addFileTap=(data)=>{
  data.fileList.forEach(item => {
    item.response.data.attachable_type=data.type
    upload.fileList.push(item.response.data)
    })
}
//下载上传文件
const downloadFile = (item) => {
  let url=''
  if(item?.info){
    url=uploadConfig.storage.OSS+item.info.url
  }else{
    url=uploadConfig.storage.OSS+item.url

  }
  window.location.href=url
}
//删除上传文件
const deleteDownload = (index) => {
  upload.fileList.splice(index, 1)
}
//tabel类型发生改变
const serviceTypeChang = (e, record, addressString) => {
  const serviceType = waybillServiceShipmentTypeMap.value[e]?.type
  if (addressList.value[serviceType]?.length === 1 && (serviceType != 4)) {
    record.address_id = addressList.value[serviceType][0].value
  } else if (addressString) {
    let listAttr=addressList.value[serviceType]?.filter(i => i.label === addressString)
    record.address_id = listAttr[0]?.value ?? ''
    if(listAttr.length){
      return;
    }
    if(record.service_type_id == 5){
      record.address = addressString
      return;
    }
    Modal.open({content: '目的地'+'“'+ addressString+'”'+'不存在,是否添加目的地',
      onOk: () => {
        addRessTap()
      },
    })
  } else {
    record.address_id = ''
  }
}
const getServiceType = function (service_type_id) {
  return waybillServiceShipmentTypeMap.value[service_type_id]?.type;
}

const getAddressListItem = (service_type_id, address_id) => {
  const serviceType = getServiceType(service_type_id)
  return addressListMap.value?.[serviceType]?.[address_id] ?? {}
}

//批量服务改变
const waybillServiceShipmentTypeChange = (e) => {
  if (selected.value.length == 0) {
    Message.warning('请至少选择一条数据操作！')
    service_id_list.value = ''
    return;
  }
  service_id_list.value = e
  formData.value.shipments.forEach((item, index) => {
    selected.value.forEach((itemInfo, indexInfo) => {
      if (item.id == itemInfo) {
        item.service_type_id = e
        item.address_id = ''
        item.address_1 = ''
        item.city = ''
        item.postcode = ''
        item.name = ''
        item.email = ''
        serviceTypeChang(item.service_type_id, item, 'init')
      }
    })
  })
}

//table 选择
//行数选中
const selected = ref([])
const setSelecteds = (key) => {
  selected.value = key
}
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
//添加table
const tabelAdd = () => {
  let userDataObj = JSON.parse(JSON.stringify(userData.value)); // 深拷贝数据
  userDataObj.id = new Date().getTime()
  formData.value.shipments.push(userDataObj)
}
//删除tabel
const deleteAction = (index) => {
  if (formData.value.shipments.length > 1) {
    formData.value.shipments.splice(index, 1)
  }
}
const userData = ref(
    {
      id: new Date().getTime(),
      urgent: 0,
      is_intercept: 0,
      service_type_id: '',
      address_id: '',
      shipment_no: '',
      parcel_count_estimate: 1,
      weight: 1.00,
      volume: 1.00,
      tray_count_estimate: 1,
      fba_id: '',
      po_number: '',
      address_1: '',
      city: '',
      postcode: '',
      name: '',
      email: '',
      remark: '',
    })

const columns = ref([
  {title:'ID',slotName: 'index',width:33},
  {
    title: '加急',
    dataIndex: 'urgent',
    slotName: 'urgent',
    type: 'slider',
    required: true,
    align: 'center',
    width: 50
  },
  {
    title: '拦截',
    dataIndex: 'is_intercept',
    slotName: 'is_intercept',
    type: 'slider',
    required: true,
    align: 'center',
    width: 50
  },
  {
    title: '服务类型',
    dataIndex: 'service_type_id',
    slotName: 'service_type_id',
    titleSlotName: 'customAgeTitle',
    type: 'select',
    required: true,
    align: 'center',
    width: 150
  },
  {
    title: '目的地',
    dataIndex: 'address_id',
    slotName: 'address_id',
    type: 'select',
    align: 'center',
    width: 150,
  },
  {
    title: '箱唛',
    dataIndex: 'shipment_no',
    slotName: 'shipment_no',
    width: 150,
    type: 'input',
    titleSlotName: 'customAgeTitle',
    required: true,
    align: 'center',
  },
  {
    title: 'CTNS',
    dataIndex: 'parcel_count_estimate',
    slotName: 'parcel_count_estimate',
    titleSlotName: 'customAgeTitle',
    width: 80,
    type: 'input',
    required: true,
    align: 'center',
  },
  {
    title: 'Weight',
    dataIndex: 'weight',
    slotName: 'weight',
    width: 80,
    titleSlotName: 'customAgeTitle',
    required: true,
    align: 'center',
  },
  {
    title: 'CBM',
    dataIndex: 'volume',
    slotName: 'volume',
    width: 80,
    titleSlotName: 'customAgeTitle',
    required: true,
    align: 'center',
  },
  {
    title: '托盘',
    width: 80,
    dataIndex: 'tray_count_estimate',
    slotName: 'tray_count_estimate',
    align: 'center',
  },
  {title: 'ID', dataIndex: 'fba_id', slotName: 'fba_id', type: 'input',width: 100, align: 'center',},
  {title: 'PO', dataIndex: 'po_number', slotName: 'po_number', type: 'input',width: 100, align: 'center',},
  {title: '备注', dataIndex: 'remark', slotName: 'remark', type: 'input',width: 200, align: 'center'},
  {title: '操作', slotName: 'fixed', fixed: 'right', width: 50, align: 'center'},
])
//合计
const summary = ({columns, data}) => {
      let countData = {
        parcel_count_estimate:0,
        weight: 0,
        volume:0,
        tray_count_estimate: 0
      };
      data.forEach(record => {
        countData.parcel_count_estimate += record.parcel_count_estimate;
        countData.weight += record.weight;
        countData.volume += record.volume;
        countData.tray_count_estimate += record.tray_count_estimate;
      })

      return [{
        urgent:'合计',
        parcel_count_estimate: countData.parcel_count_estimate.toFixed(2),
        weight: countData.weight.toFixed(2),
        volume: countData.volume.toFixed(2),
        tray_count_estimate: countData.tray_count_estimate.toFixed(2),
      }]
    }
const onShow = async (value) => {
  visible.value = true
  let userDataObj = JSON.parse(JSON.stringify(userData.value)); // 深拷贝数据
  userDataObj.id = new Date().getTime()
  formData.value.shipments.push(userDataObj)
  waybillServiceTypeListData()

  //编辑
  if (value) {
    loading.value = true
    infoGet(value.id)
    waybillServiceShipmentTypeListData()
  }

}


/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
//   open: false,
  // 弹出层标题（用户导入）
  title: "",
  fileList: [],
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + tool.getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_URL + "/system/uploadFile"
});

const emits = defineEmits(['addClick', 'emitClick'])
//新增 //编辑
const handleBeforeOk = async (formEl) => {
  // return false
  let formParse = JSON.parse(JSON.stringify(formData.value)); // 深拷贝数据
  formParse.files=[]
  upload.fileList?.map((item, index) => {
    let obj={
      hash:item?.info?.hash || item?.hash,
      type:item.attachable_type
    }
    formParse.files.push(obj)
  })
  console.log(formParse)
  for (let i = 0; i < formParse.shipments.length; i++) {
    if (!formParse.shipments[i].service_type_id) {
      Message.error('第' + (i + 1) + '行服务类型必填')
      return;
    }

    const serviceType = waybillServiceShipmentTypeMap.value[formParse.shipments[i].service_type_id]?.type
    if (!formParse.shipments[i].address_id && (serviceType !== 4)) {
      Message.error('第' + (i + 1) + '行目的地必填')
      return;
    }
    if (!formParse.shipments[i].shipment_no) {
      Message.error('第' + (i + 1) + '行箱唛必填')
      return;
    }
    if (!formParse.shipments[i].parcel_count_estimate) {
      Message.error('第' + (i + 1) + '行CTNS必填')
      return;
    }
  }
  if(tableFile.value?.file){
    let res= await common.uploadFile({file:tableFile.value.file})
    let obj={
      hash:res.data?.hash,
      type:'2'
    }
    formParse.files.push(obj)
  }
  // let parcelList = userData.value.filter(item => item.service_type_id!== null);
  // formParse.shipments=userData.value
  if (!formEl) return
  await formEl.validate((valid) => {
    if (!valid) {
      loading.value = true
      if (formParse.id == '') {
        waybill.save(formParse).then(res => {
          Message.success(res.message || `新增成功！`)
          emits('addClick');
          close()
        }).catch(() => {
          loading.value = false;
        });
      } else {
        waybill.update(formParse).then(res => {
          Message.success(res.message || `编辑成功！`)
          emits('addClick');
          close()
        }).catch(() => {
          loading.value = false;
        });
      }

    }
  })

};


const close = () => {
  formData.value = {
    id: '',
    depot_id: "",
    number: "",
    container_no: "",
    container_type: "",
    type: "1",
    service_id: "",
    carrier: "",
    etd: "",
    eta: "",
    received_at: "",
    departure: "",
    destination: "",
    exportwith: "0",
    frame: "0",
    weight_volume: '1',
    shipments: [],
    files: []
  }
  tableFile.value={}
  upload.fileList = []
  waybillServiceShipmentTypeList.value = []
  formData.value.id = ''
  service_id_list.value = ''
  loading.value = false
  // formRef.value.resetFields();
  visible.value = false


}
const onBeforeCancel = () => {
  Modal.confirm({
    title: '确认关闭?',
    onOk: () => {
      close()
    },
  });
}
defineExpose({onShow})

</script>

<template>
  <a-drawer v-model:visible="visible" v-if="visible" width="90%" :onBeforeCancel="onBeforeCancel" @click="stopEditing(null)">
    <template #title>
      <div>{{ formData.id == "" ? '新增' : '编辑' }}</div>
    </template>
    <template #footer>
      <div style="display: flex; justify-content: space-between;align-items: center;">
        <div style="color: rgb(50 193 148);">tips：先选择"服务项目"后在操作明细,请按要求填写(导入)单据信息
        </div>
        <div>
          <a-button @click="visible = false" style="margin-right: 20px;">关闭</a-button>
          <a-button type="primary" :disabled="loading" @click="handleBeforeOk(formRef)">
            保存
          </a-button>
        </div>
      </div>
    </template>
    <a-spin dot :loading="loading">
      <a-form ref="formRef" :rules="rules" :model="formData">
        <div class="form-top-main">
          <a-col :span="span">
            <a-form-item field="size" label="类型">
              <a-radio-group v-model="formData.type" @change="typeChang" type="button">
                <a-radio value="1">海运订单</a-radio>
                <a-radio value="2">空运订单</a-radio>
                <a-radio value="3">第三方转入</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item field="depot_id" label="转运仓库" validate-trigger="change">
              <a-select v-model="formData.depot_id" :options="columnsDist.dicthelpApi_depot.data"
                        :field-names="{ value: 'id', label: 'name' }"
                        placeholder="请选择转运仓库" allow-clear allow-search :virtual-list-props="{height:200}"/>
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item field="number" :label="formData.type=='3' ? '入仓号':'提单号'" validate-trigger="change">
              <a-input v-model="formData.number" placeholder="请输入提单号"/>
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type=='1'">
            <a-form-item field="container_no" label="柜号" validate-trigger="change">
              <a-input v-model="formData.container_no" placeholder="请输入柜号"/>
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type=='1'">
            <a-form-item field="container_type" label="柜型" validate-trigger="change">
              <a-select v-model="formData.container_type" :options="columnsDist.dictObj.data.containerType"
                        :field-names="{ value: 'key', label: 'title' }"
                        placeholder="请选择柜型" allow-clear allow-search :virtual-list-props="{height:200}"/>
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item field="service_id" :label="formData.type=='3' ? '入仓类型':'服务项目'" label=""
                         validate-trigger="change">
              <a-select v-model="formData.service_id" @change="waybillServiceShipmentTypeListData"
                        :options="waybillServiceTypeList" :field-names="{ value: 'id', label: 'name' }"
                        :placeholder="formData.type=='3' ? '请选择入仓类型':'请选择服务项目'" allow-search
                        :virtual-list-props="{height:200}"/>
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type=='1'">
            <a-form-item field="carrier" label="承运商" validate-trigger="change">
              <a-select v-model="formData.carrier" :options="columnsDist.dictObj.data.waybill_carrier"
                        :field-names="{ value: 'key', label: 'title' }"
                        placeholder="请选择承运商" allow-clear allow-search :virtual-list-props="{height:200}"/>
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type!='3'">
            <a-form-item field="etd" label="ETD" validate-trigger="change">
              <a-date-picker
                  style="width: 100%;"
                  placeholder="请选择出发时间"
                  v-model="formData.etd"
              />
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type!='3'">
            <a-form-item field="eta" label="ETA" validate-trigger="change">
              <a-date-picker
                  style="width: 100%;"
                  placeholder="请选择到港时间"
                  v-model="formData.eta"
              />
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type=='3'">
            <a-form-item field="received_at" label="入仓时间" validate-trigger="change">
              <a-date-picker
                  style="width: 100%;"
                  placeholder="请选择入仓时间"
                  v-model="formData.received_at"
              />
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type=='1'">
            <a-form-item field="departure" label="起运港" validate-trigger="change">
              <a-select v-model="formData.departure" :options="columnsDist.dicthelpApi_place.data"
                        :field-names="{ value: 'id', label: 'name' }"
                        placeholder="请选择起运港" allow-clear allow-search :virtual-list-props="{height:200}"/>
            </a-form-item>
          </a-col>
          <a-col :span="span" v-if="formData.type!='3'">
            <a-form-item field="destination" label="目的港" validate-trigger="change">
              <a-select v-model="formData.destination" :options="columnsDist.dicthelpApi_place.data"
                        :field-names="{ value: 'id', label: 'name' }"
                        placeholder="请选择目的港" allow-clear allow-search :virtual-list-props="{height:200}"/>
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item label="描述" field="describe">
              <a-textarea v-model="formData.describe" placeholder="请输入描述"/>
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item label="备注" field="remark">
              <a-textarea v-model="formData.remark" placeholder="请输入备注" auto-size/>
            </a-form-item>
          </a-col>
        </div>
        <a-tabs default-active-key="1">

          <a-tab-pane key="1" title="货件">
            <div style="display: flex;justify-content: space-between;align-items: center;">
              <div class="tab-main">
                <a-switch :checked-value="1" :unchecked-value="0" v-model="formData.exportwith">
                  <template #checked>
                    清关服务
                  </template>
                  <template #unchecked>
                    无需清关
                  </template>
                </a-switch>
                <a-switch :checked-value="1" :unchecked-value="0" v-model="formData.frame">
                  <template #checked>
                    自带车架
                  </template>
                  <template #unchecked>
                    不带车架
                  </template>
                </a-switch>
                <a-button type="primary" @click="addRessTap">添加目的地</a-button>

                <!-- <a-radio-group v-model="formData.weight_volume" type="button">
                  <a-radio value="1">KG</a-radio>
                  <a-radio value="2">LB</a-radio>
                </a-radio-group> -->
                <a-col :span="span">
                  <a-form-item label="" validate-trigger="change">
                    <a-select @change="waybillServiceShipmentTypeChange" v-model="service_id_list"
                              :disabled="waybillServiceShipmentTypeList.length === 0 || selected.length === 0"
                              :options="waybillServiceShipmentTypeList" :field-names="{ value: 'id', label: 'name' }"
                              placeholder="设置服务类型（批量）" style="width: 400px;" allow-search
                              :virtual-list-props="{height:200}"/>
                  </a-form-item>
                </a-col>
                <div style="margin-left: 10px;">
                  <a-upload name="file" :multiple="false" :show-file-list="false" :auto-upload="false"
                            accept=".xlsx, .xls" @change="handleUpload" :disabled="waybillServiceShipmentTypeList.length === 0">
                    <a-button type="success" icon="download" >Excel上传</a-button>
                  </a-upload>
                  <a-link title="下载模版" @click="downloadTap()" style="margin-left: 20px;">
                    <icon-to-bottom/>
                    下载模版
                  </a-link>
                </div>
              </div>
              <div>
                <icon-plus-circle :size="26" @click="tabelAdd" style="cursor: pointer;"/>
              </div>
            </div>
            <a-table v-if="formData.shipments!=''" ref="tableRef" row-key="id" :columns="columns"
                     :data="formData.shipments" :row-selection="rowSelection" v-model:selectedKeys="selected"
                     :summary="summary"
                     @selection-change="setSelecteds($event)" :bordered="false" size="mini" column-resizable
                     :pagination="false">
              <template #index="{rowIndex}">{{rowIndex+1}}</template>
              <template #customAgeTitle="{column}">
                <div>
                  <span style="color:red;">*</span>{{ column.title }}
                </div>
              </template>
              <template #urgent="{ record,rowIndex }">
                <a-switch :checked-value="1" :unchecked-value="0" v-model="record.urgent"
                          v-if="tableEditingIndex[rowIndex]">
                  <template #checked>是</template>
                  <template #unchecked>否</template>
                </a-switch>
                <span v-else>{{ record.urgent == 1 ? '是' : '否' }}</span>
              </template>
              <template #is_intercept="{ record,rowIndex }">
                <a-switch :checked-value="1" :unchecked-value="0" v-model="record.is_intercept"
                          v-if="tableEditingIndex[rowIndex]">
                  <template #checked>是</template>
                  <template #unchecked>否</template>
                </a-switch>
                <span v-else>{{ record.is_intercept == 1 ? '是' : '否' }}</span>
              </template>

              <template #service_type_id="{ record,rowIndex }">
                <a-select :options="waybillServiceShipmentTypeList" @change="serviceTypeChang($event,record)"
                          v-if="tableEditingIndex[rowIndex]"
                          placeholder="请选择" :field-names="{ value: 'id', label: 'name' }"
                          v-model="record.service_type_id"/>
                <span v-else>{{ waybillServiceShipmentTypeMap[record.service_type_id]?.name }}</span>
              </template>
              <template #address_id="{ record ,rowIndex}">
                <template v-if="tableEditingIndex[rowIndex]">
                  <a-select placeholder="请选择" v-model="record.address_id"
                            :virtual-list-props="{}" :options="addressListChang(record)"
                            allow-search v-if="record.service_type_id != 5 || !record.address">
                  </a-select>
                  <a-textarea v-else v-model="record.address"/>
                </template>
                <a-popover placement="right" trigger="hover" v-else-if="!record.address">
                  <div>{{  getAddressListItem(record.service_type_id, record.address_id)?.code }}</div>
                  <template #content>
                    <div>{{ getAddressListItem(record.service_type_id, record.address_id)?.address_1 }}</div>
                    <div>{{ getAddressListItem(record.service_type_id, record.address_id)?.city }}</div>
                    <div>{{ getAddressListItem(record.service_type_id, record.address_id)?.postcode }}</div>
                    <div>{{ getAddressListItem(record.service_type_id, record.address_id)?.name }}</div>
                    <div>{{ getAddressListItem(record.service_type_id, record.address_id)?.email }}</div>
                  </template>
                </a-popover>
                <span v-else>{{ record.address }}</span>
              </template>
              <template #shipment_no="{ record,rowIndex }">
                <a-input v-model="record.shipment_no" placeholder="请输入" v-if="tableEditingIndex[rowIndex]"/>
                <span v-else>{{ record.shipment_no }}</span>
              </template>
              <template #parcel_count_estimate="{ record,rowIndex }">
                <a-input-number v-model="record.parcel_count_estimate" placeholder="请输入" :min="1" :hide-button="true"
                                v-if="tableEditingIndex[rowIndex]"/>
                <span v-else>{{ record.parcel_count_estimate }}</span>
              </template>
              <template #weight="{ record,rowIndex }">
                <a-input-number v-model="record.weight" placeholder="请输入" :min="0.01" :step="0.01"
                                :hide-button="true" v-if="tableEditingIndex[rowIndex]"/>
                <span v-else>{{ record.weight }}</span>
              </template>
              <template #volume="{ record,rowIndex }">
                <a-input-number v-model="record.volume" placeholder="请输入" :min="0.01" :step="0.01"
                                @change="(value, ev) => getTrayCount(record,value)" v-if="tableEditingIndex[rowIndex]"/>
                <span v-else>{{ record.volume }}</span>
              </template>
              <template #fba_id="{ record,rowIndex }">
                <a-input v-model="record.fba_id" placeholder="请输入" v-if="tableEditingIndex[rowIndex]"/>
                <span v-else>{{ record.fba_id }}</span>
              </template>
              <template #po_number="{ record,rowIndex }">
                <a-input v-model="record.po_number" placeholder="请输入" v-if="tableEditingIndex[rowIndex]"/>
                <span v-else>{{ record.po_number }}</span>
              </template>
              <template #remark="{ record,rowIndex }">
                <a-textarea v-model="record.remark" placeholder="请输入" auto-size v-if="tableEditingIndex[rowIndex]"/>
                <div v-else style="white-space: pre-line;">{{ record.remark }}</div>
              </template>
              <template #fixed="{ rowIndex  }">
                <a-link title="删除" @click="deleteAction(rowIndex)">
                  <icon-delete/>
                </a-link>
              </template>
              <template #tr="{ rowIndex}">
                <tr @click.stop.prevent="startEditing(rowIndex)"></tr>
              </template>
              <template #summary-cell="{ column,record,rowIndex }">
                <div style="color:red">{{record[column.dataIndex]}}</div>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" title="附件">
            <a-button type="primary" icon="download" style="margin-top: 10px;" @click="downloadAdd">附件上传</a-button>
              <div>
                <div v-for="(item,index) in upload.fileList" :key="item.id" style="display: flex;margin-top: 10px;justify-content: space-between;padding: 0 10px;background: #ddd;">
                  <div>{{item.filename || item.origin_name}}</div>
                  <div>类型：{{getDictData('dictObj','AttachmentType',item.attachable_type,2,columnsDist) }}</div>
                  <div>上传时间：{{item.created_at}}</div>
                  <div>
                    <a-link  title="下载" @click="downloadFile(item)"><icon-to-bottom /></a-link>
                    <a-link title="删除" @click="deleteDownload(index)"><icon-delete/></a-link>
                  </div>
                </div>
              </div>
            <!-- <a-upload style="margin-top: 10px;" v-model:file-list="upload.fileList" :action="upload.url" multiple
                      :limit="5" :headers="upload.headers"/> -->
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
    <add-ress ref="addressRef" @addClickRess="addAll"/> 
    <file-type ref="filetypeRef" @addFile="addFileTap"/> 

  </a-drawer>

</template>
<style>
.form-top-main {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.tab-main {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.tab-main .arco-form-item {
  margin-bottom: 0;
}

.tab-main .arco-switch {
  margin-right: 20px;
}
</style>